package com.uvt.agenda;

import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;

import com.uvt.agenda.adapter.EventAdapter;

/**
 * Created by Cristi on 2/2/14.
 */
public class CheckHolidays {

    static ArrayList<Holiday> holidays = new ArrayList<Holiday>();
    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    private static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            is.close();
        }
    }

    private static ArrayList<Holiday> getHolidays(final int year) {
        AsyncTask<String, String, String> asyncTask = new AsyncTask<String, String, String>() {
            @Override
            protected String doInBackground(String... params) {

                try {
                    String url = "https://api.xmltime.com/holidays?accesskey=gwcMQsX4bM&secretkey=MEtb16JsiJ0HSynMYpsi&out=js&country=ro&lang=ro&year=" + year;
                    JSONObject json = readJsonFromUrl(url);

                    JSONArray holidays_data = json.getJSONArray("holidays");
                    int holidays_count = holidays_data.length();
                    holidays.clear();
                    for (int pos = 0; pos < holidays_count; pos++) {
                        Holiday current_holiday = new Holiday();
                        current_holiday.setId(Integer.parseInt(holidays_data.getJSONObject(pos).get("id").toString()));
                        current_holiday.setName(holidays_data.getJSONObject(pos).get("name").toString());
                        current_holiday.setDescription(holidays_data.getJSONObject(pos).get("oneliner").toString());
                        current_holiday.setYear(year);
                        current_holiday.setMonth(Integer.parseInt(holidays_data.getJSONObject(pos).getJSONObject("date").getJSONObject("datetime").get("month").toString()));
                        current_holiday.setDay(Integer.parseInt(holidays_data.getJSONObject(pos).getJSONObject("date").getJSONObject("datetime").get("day").toString()));
                        holidays.add(current_holiday);
                    }
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    return "";
                }
            }

        };

        asyncTask.execute();
        return holidays;

    }

    public static ArrayList<Event> getHolidaysEvents(int year, int month, int day) throws IOException, JSONException {
        ArrayList<Event> result = new ArrayList<Event>();
        ArrayList<Holiday> holidays = getHolidays(year);

        for (Holiday holiday : holidays) {
            if (holiday.getMonth() == month &&
                    holiday.getDay() == day) {
                result.add(EventAdapter.toEvent(holiday));
            }
        }
        return result;
    }

    public static ArrayList<Event> getHolidaysEvents(int year, int month) throws IOException, JSONException {
        ArrayList<Event> result = new ArrayList<Event>();
        ArrayList<Holiday> holidays = getHolidays(year);

        for (Holiday holiday : holidays) {
            if (holiday.getMonth() == month) {
                result.add(EventAdapter.toEvent(holiday));
            }
        }
        return result;
    }

    public static ArrayList<Event> getHolidaysEvents(int year) throws IOException, JSONException {
        ArrayList<Event> result = new ArrayList<Event>();
        ArrayList<Holiday> holidays = getHolidays(year);

        for (Holiday holiday : holidays) {
            result.add(EventAdapter.toEvent(holiday));
        }
        return result;
    }
}
